package cn.wizzer.app.web.modules.controllers.open;

import cn.wizzer.app.web.commons.constant.ApiConstant;
import cn.wizzer.app.web.commons.ulog.annotation.ULog;
import cn.wizzer.framework.util.Result;
import cn.wizzer.framework.base.model.enums.BizExceptionEnum;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Files;
import org.nutz.lang.random.R;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.impl.AdaptorErrorContext;
import org.nutz.mvc.upload.TempFile;
import org.nutz.mvc.upload.UploadAdaptor;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.Locale;

@IocBean
@At("/open/upload")
public class ApiUploadController {
    private static final Log log = Logs.get();

    @AdaptBy(type = UploadAdaptor.class, args = {"ioc:imageUpload"})
    @At
    @Ok("json")
    @ULog(tag = "用户图片上传到本地")
    public Object image(@Param("Filedata") TempFile tf, HttpServletRequest req, AdaptorErrorContext err) {
        try {
            if (err != null && err.getAdaptorErr() != null) {
                return Result.error(BizExceptionEnum.FILE_ILLEGAL);
            } else if (tf == null) {
                return Result.error(BizExceptionEnum.EMPTY_FILE);
            } else {
                String uri = "/image/" + DateFormatUtils.format(new Date(), "yyyyMMdd", Locale.CHINA) + "/" + R.UU32() + tf.getSubmittedFileName().substring(tf.getSubmittedFileName().indexOf("."));
                String f = ApiConstant.APP_UPLOAD_BASE + uri;
                Files.write(new File(f), tf.getInputStream());
                log.info("文件上传到本地, 文件名: " + tf.getName());
                return Result.success(BizExceptionEnum.UPLOAD_SUCCESS, uri);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        } catch (Throwable e) {
            return Result.error(BizExceptionEnum.PICTURE_FORMAT_INCORRECT);
        }
    }
}
